import { defineStore } from 'pinia';
import { UserState } from './types';
import global from '@/global';
import { setToken, clearToken } from '@/utils/auth';
import { login as userLogin, logout as userLogout, getUserInfo, LoginData } from '@/api/login';
import {encrypt} from '@/utils/jsencrypt';

const useUserStore = defineStore('user', {
    state: (): UserState => ({
		userId: undefined,
		username: undefined,
		nickName: undefined,
		avatar: undefined,
		gender: undefined,
		email: undefined,
		phone: undefined,
		status: undefined,
		registrationDate: undefined,
		roles: [],
		roleName: undefined,
	}),
	getters: {
	    userInfo(state: UserState): UserState {
	      return { ...state };
	    },
	},
	actions: {
		// 登录
		async login(loginForm: LoginData) {
		  try {
			loginForm.password = encrypt(loginForm.password);
		    const res = await userLogin(loginForm);
		    if (res.data) {
		      setToken(res.data.tokenValue);
			  await this.info();
		    } else {
		      throw new Error(res.msg);
		    }
		  } catch (err) {
		    clearToken();
		    throw err;
		  }
		},
		// 获取用户信息
		async info() {
		  const res = await getUserInfo();
		  if (res.data.avatar) {
			res.data.avatar = global.baseUrl + res.data.avatar;
		  }
		  this.setInfo(res.data);
		},
		// 缓存用户信息
		setInfo(partial: Partial<UserState>) {
		  this.$patch(partial);
		},
		// 清除缓存信息
		resetInfo() {
		  this.$reset();
		},
		// 退出登录
		async logout() {
			try {
			  await userLogout();
			} finally {
			  this.logoutCallBack();
			}
		},
		logoutCallBack() {
		  this.resetInfo();
		  clearToken();
		},
	}
})

export default useUserStore;